package com.example.demo.controllers;

import com.example.demo.common.utils.ToolsUtil;
import com.example.demo.dao.KHRepository;
import com.example.demo.entity.KH;
import com.example.demo.services.KHService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RequestMapping("/registerinfo")
@Controller
public class RegisterController {

    @Autowired
    private KHService khService;

    @Autowired
    private KHRepository khRepository;

    @RequestMapping("/register")
    @ResponseBody
    public Map<String, Object> register(HttpServletRequest request, Model model){
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String password_again = request.getParameter("password_again");
            String phone = request.getParameter("phone");

            KH users = khService.findUser(username);
            if (users!=null){
                return ToolsUtil.returnMessage(1,"用户名已存在");
            }
            KH kh = new KH();
            kh.setKno(username);
            kh.setKpw(password);
            kh.setKtelephone(phone);
            khRepository.save(kh);
            return ToolsUtil.returnMessage(2,"注册成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return ToolsUtil.returnMessage(0,"注册失败");
    }
}
